package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.AlipayConstant;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.mapper.TbPayLogMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.AddRessService;
import com.dongdongshop.service.OrderItemService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.PayLogService;
import com.dongdongshop.util.IdWorker;
import org.apache.ibatis.jdbc.Null;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @ClassName OrderServiceImpl
 * @Author RC
 * @date 2020.12.23 08:52
 */
@Component
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddRessService addRessService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private TbOrderItemMapper tbOrderItemMapper;
    @Resource
    private TbOrderMapper tbOrderMapper ;
    @Resource
    private TbPayLogMapper tbPayLogMapper;
    @Reference(timeout = 100000,check = false)
    private OrderItemService orderItemService ;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Transactional
    @Override
    public Map<String,Object> saveOrderList(Long id, String userId, String sumPrice) {
        //根据收件人id获取 地址
        TbAddress address = addRessService.getInfoById(id);
        //母订单号
        IdWorker idWorker2 = new IdWorker();
        Long tradeId= idWorker2.nextId();
        //总金额
        double sumMoney = 0;
        //获取用户reds缓存的购物车数据
        List<Cart> cartList = (List<Cart>)redisTemplate.boundHashOps("cartList").get(userId);
        List<TbOrderItem> orderItemList = new ArrayList<>();
        //遍历redis缓存数据
        double money = 0;
        for (Cart cart : cartList) {
            IdWorker idWorker = new IdWorker();
            long orderId = idWorker.nextId();
            Long l=100l;
            TbOrder order = new TbOrder();
            l++;
            order.setOrderId(orderId+l);
            order.setUserId(userId);
            order.setPaymentType("1");//支付方式
            order.setStatus("1");//支付状态,未付款
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setReceiverAreaName(address.getAddress());
            order.setReceiver(address.getContact());
            order.setReceiverMobile(address.getMobile());
            order.setTradeId(tradeId);
            order.setSellerId(cart.getSellerId());
            for (TbOrderItem orderItem : cart.getOrderItemList()) {
                //落库到明细表
               orderItem.setId(idWorker.nextId());
               orderItem.setOrderId(order.getOrderId());
               orderItemList.add(orderItem);
               money += orderItem.getTotalFee().doubleValue();
                tbOrderItemMapper.insert(orderItem);
                //tbOrderItemMapper.insertOrderItemAll(orderItemList);
            }
            order.setPayment(new BigDecimal(money));//金额累计
            tbOrderMapper.insert(order);
     }
        sumMoney = money;
        //下单成功清空购物车
       /* redisTemplate.boundHashOps("cartList").delete(userId);*/
        redisTemplate.boundHashOps(AlipayConstant.TRADE_ID + userId).put(tradeId,cartList);
        redisTemplate.boundHashOps(AlipayConstant.TRADE_ID + userId).expire(1, TimeUnit.HOURS);
        //发送mq
        /*rocketMQTemplate.syncSend("pay_topic", MessageBuilder.withPayload(order.getTradeNo()).build()
                ,2000,2);
        System.out.println("发送时间："+System.currentTimeMillis());*/

        Map<String,Object> map = new HashMap<>();
        map.put("trade_no",tradeId);//母单号   必填
        map.put("amount",sumMoney);//总金额    必填
        map.put("subject","第一次订单");//商品名称 必填
        map.put("body","测试---->>>>");//描述 可空
        return map;
    }

    @Override
    public List<OrderDTO> getMyOrder(String username) {

        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(username);

        List<TbOrder> orderList = tbOrderMapper.selectByExample(example);

        //传一个list集合用来装orderDTOS
        List<OrderDTO> orderDTOS = new ArrayList<>();
        //遍历查询出的订单数据
        for (TbOrder tbOrder : orderList) {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setOrderId(tbOrder.getOrderId());
            orderDTO.setCreateTime(tbOrder.getCreateTime());
            orderDTO.setSellerId(tbOrder.getSellerId());
            orderDTO.setStatus(tbOrder.getStatus());
            //查询明细数据
            List<TbOrderItem> orderItems = tbOrderItemMapper.selectoRderItemByOrderId(tbOrder.getOrderId());
            orderDTO.setOrderItem(orderItems);
            orderDTOS.add(orderDTO);
        }
        return orderDTOS;
    }

    //根据out_trade_no查询订单 母订单
    @Override
    public List<TbOrder> getOrderByOutTradeNo(String out_trade_no) {
        return tbOrderMapper.getOrderByOutTradeNo(out_trade_no);
    }

    @Override
    public Map<String, Object> refund(Long id) {
        TbOrderItem orderItem = tbOrderItemMapper.selectByPrimaryKey(id);
        /*TbOrder order = tbOrderMapper.getOrderByOrderId(orderItem.getOrderId());*/
        TbOrder order = tbOrderMapper.selectByPrimaryKey(orderItem.getOrderId());
        TbPayLog payLog = tbPayLogMapper.getInfoByTradeId(order.getTradeId());
        Map<String,Object> map = new HashMap<>();

            //String out_trade_no, 商户订单号，商户网站订单系统中唯一订单号
            // tring trade_no, 支付宝交易号
            // String refund_amount,   需要退款的金额，该金额不能大于订单金额，必填
            // String refund_reason,   退款的原因说明
            // String out_request_no   标识一次退款请求，同一笔交易多次退款需要保证唯
          map.put("out_trade_no",payLog.getOutTradeNo());
          map.put("trade_no",payLog.getTransactionId());
          map.put("refund_amount",orderItem.getTotalFee());
          map.put("refund_reason","不想买了");
          map.put("out_request_no",orderItem.getId());

        return map;

    }
    //支付成功修改订单状态为已支付
    @Override
    public void updateOrderStatus(String out_trade_no) {
        String status = "2";

        tbOrderMapper.updateOrderStatus(status,out_trade_no);
    }

    @Override
    public void updateOrderRefundStatus(String widtRout_trade_no) {
        String status = "8";
        tbOrderMapper.updateOrderRefundStatus(status,widtRout_trade_no);
    }

    @Override
    public boolean sendMQService(String out_trade_no, String trade_no, String totalFee) {

        // 根据商户订单号查询
        List<TbOrder> orderList = tbOrderMapper.getOrderByOutTradeNo(out_trade_no);

        // 获取用户id

        String userId = orderList.get(0).getUserId();

        Map<String, String> map = new HashMap<>();

        map.put("userId", userId);

        map.put("totalFee", totalFee);

        // message 是需要发送给接收方的数据
        String msg = JSONObject.toJSONString(map);
        Message message = MessageBuilder.withPayload(msg).build();

        // 保存或者修改数据库所需要的所有参数

        Map<String, Object> map1 = new HashMap<>();

        map1.put("out_trade_no", out_trade_no);

        map1.put("trade_no", trade_no);

        map1.put("totalFee", totalFee);

        map1.put("userId", userId);

        map1.put("orderList", orderList);
        // 第一个参数txProducerGroup ： 事务的组

        // 最后一个参数 arg : 是发送方本地保存或者修改数据库所需要的所有参数

        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction("tx-group-order","create_score", message, map1);

        return true;
    }

    @Override
    public Map<String, Object> getOrderAll(String sellerId) {
        //当前是2021年
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int year = c.get(Calendar.YEAR);
//当前年(2021)的第一天
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
//当前年的第一天的前一年的时间
        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
        ca.setTime(currYearFirst); //设置时间为当前时间
        ca.add(Calendar.YEAR, -1); //年份减1
        Date lastMonth = ca.getTime();

        List<TbOrder> list = tbOrderMapper.getSeller(sellerId,lastMonth,currYearFirst);

        List<Integer> count = new ArrayList<>();
        List<String> mounth = new ArrayList<>();

        for (TbOrder order : list) {
            count.add(order.getCount());
            mounth.add(order.getMounth());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("mounth",mounth);
        return map;

    }

    @Override
    public  Map<String,Object> getMonthlySales(String sellerId) {
        System.out.println("111");
        List<OrderVO> orderList = tbOrderMapper.getMonthlySales(sellerId);
        System.out.println(orderList.toString());
        Map<String,Object> map = new HashMap();
        List<Integer> feeList = new ArrayList<>();
        List tList = new ArrayList<>();
        List hList = new ArrayList<>();
        int[] lastYear = {22,33,44,55,88,99,11,222,11,99,100,200};
        for (OrderVO orderVO : orderList) {
            feeList.add(orderVO.getFee());
        }
        DecimalFormat df = new DecimalFormat();
        //同比统计  今年 - 去年 / 去年
        for (int i = 0; i < feeList.size(); i++) {
            //double tb = (feeList.get(i) - lastYear[i]) / lastYear[i] ;
            String tb = df.format((float)((feeList.get(i) - lastYear[i]) * 100) /  lastYear[i]);
            tList.add(tb);
        }
        //环比计算 当月 - 上月 / 上月
        for (int i = 0; i < feeList.size(); i++) {
            if(i != 0){
                //double hb = (feeList.get(i) - feeList.get(i-1)) / feeList.get(i-1);
                String hb = df.format((float)((feeList.get(i) - feeList.get(i-1)) * 100) / feeList.get(i-1));
                hList.add(hb);
            }else {
                double hb= 0;
                hList.add(hb);
            }
        }
        map.put("fee",feeList);
        map.put("tb",tList);
        map.put("hb",hList);
        return map;
    }
}

